import re
import gtk
import main
import chat
import socket
import server
import threading
import TCPServer
import chat_list


class ClientThread(threading.Thread):
    
    def __init__(self, iter, uname, ip, is_open, data = None):
        self.iter     = iter
        self.username = uname
        self.ip       = ip
        self.is_open  = is_open
        self.data     = data
        
        threading.Thread.__init__(self)
        
    def run(self, data = None):
        if self.is_open:
            win = chat_list.search(self.username)
        else:
            win = chat.WndChat(self.iter, self.username, self.ip, False)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        win.socket = sock
        win.push_status("Connecting to " + self.username + "...")
        sock.connect((self.ip, TCPServer.PORT))
        sock.send("/open " + server.username)
        
        if self.data != None:
			sock.send(self.data)
			data = None

        win.status = True
        while (win.status):
            data = sock.recv(1024)
            
            if data == "" : return
            
            rep = re.compile('/([^ ]+) ([^ ]+)')
            req = rep.match(data)
            if req != None:
                action = req.group(1)
                
                if action == 'close':
                    sock.close()
                    win.push_status(self.username + " has left the conversation.")
                    #win._builder.get_object("txt_chat_message").set_sensitive(False)
                    win.status = False
                    
                elif action == 'ack':
                    win.push_status("Connection established.")
                    
            else:
                # print "Client receiving data..."
                # print self.username + " is receiving data"
                win.inject_data(data)
